// 页面主色调
import 'dart:io';

import 'package:abc/controller/withdraw_controller.dart';
import 'package:abc/page/withdraw_record_page.dart'; // 添加导入
import 'package:abc/view/CustomAppBar.dart';
import 'package:abc/view/GradientButton.dart';
import 'package:abc/view/NoneStyleInputField.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';


const Color darkBg = Color(0xFF1C1C2B);
const Color textColor = Colors.white;

class WithdrawPage extends GetView<WithdrawController> {
  const WithdrawPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (!Get.isRegistered<WithdrawController>()) {
      Get.lazyPut(() => WithdrawController());
    }
    return Scaffold(
      backgroundColor: const Color(0xFF0E0F26), // 深色背景
      appBar: CustomAppBar(
        title: "提现",
        onBack: () {
          Get.back();
        },
        rightText: '提现记录',
        onRightTextTap: () {
          Get.to(() => const WithdrawRecordPage()); // 跳转到提现记录页面
        },
      ),
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            //  收益余额卡片
            SliverToBoxAdapter(child: _buildEarningsCard(darkBg, textColor)),

            //  TabBar 悬浮
            SliverPersistentHeader(
              delegate: _SliverAppBarDelegate(
                TabBar(
                  controller: controller.tabController,
                  padding: EdgeInsets.all(0),
                  labelPadding: EdgeInsets.zero,
                  dividerHeight: 0.5,
                  indicatorPadding: EdgeInsets.fromLTRB(
                    0.0,
                    kTextTabBarHeight - 3,
                    0.0,
                    0.0,
                  ),
                  indicator: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(2),
                    ),
                  ),

                  indicatorSize: TabBarIndicatorSize.label,
                  labelStyle: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                  unselectedLabelStyle: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                  labelColor: Colors.white,
                  unselectedLabelColor: Colors.white54,
                  tabs: controller.tabs.map((name) => Tab(text: name)).toList(),
                ),
              ),
              pinned: true, // TabBar 固定在顶部
            ),
          ];
        },
        // 4. 主体 TabBarView
        body: TabBarView(
          controller: controller.tabController,
          children: <Widget>[
            bankWidget(),
            weChatOrAliPayWidget(),
            weChatOrAliPayWidget(),
            usdtWidget(),
          ],
        ).paddingSymmetric(vertical: 10, horizontal: 16),
      ),
    );
  }

  // ---  收益卡片 ---
  Widget _buildEarningsCard(Color bgColor, Color textColor) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 22),
      decoration: BoxDecoration(
        color: Color(0x33959595),
        borderRadius: BorderRadius.circular(10),
      ),

      child: Column(
        children: [
          Text(
            '24985',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 6),
          Text(
            '您的收益余额（元）',
            style: TextStyle(color: Color(0xFF999999), fontSize: 13),
          ),
        ],
      ),
    ).paddingSymmetric(horizontal: 16, vertical: 10);
  }

  // ---  银行 ---
  Widget bankWidget() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //姓名、银行卡号
          Container(
            padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 24),
            decoration: BoxDecoration(
              color: Color(0x33959595),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '姓名',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 6),
                NoneStyleInputField(
                  hintText: '请输入姓名',
                  contentPadding: EdgeInsets.all(0),
                  onTextChanged: (value) {
                    controller.name.value = value;
                  },
                ),
                SizedBox(height: 15),
                Text(
                  '银行卡号',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 6),
                NoneStyleInputField(
                  hintText: '请输入银行卡号',
                  contentPadding: EdgeInsets.all(0),
                  keyboardType: TextInputType.number, // 设置数字键盘
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                  ],
                  onTextChanged: (value) {
                    controller.bankCardNumber.value = value;
                  },
                ),

              ],
            ),
          ),
          SizedBox(height: 10),
          //提现金额
          withdrawalAmount(),
          SizedBox(height: 6),

          getBottomWidget(),
        ],
      ),
    );
  }

  // ---  输入提现金额 ---
  Widget withdrawalAmount() {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 20),
      decoration: BoxDecoration(
        color: Color(0x33959595),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '提现金额（手续费5%）',
            style: TextStyle(
              color: Colors.white,
              fontSize: 15,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 25),
          Row(
            children: [
              Text(
                '￥',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 40,
                  fontWeight: FontWeight.w500,
                  height: 1,
                ),
              ),

              Expanded(
                child: NoneStyleInputField(
                  hintText: '',
                  contentPadding: EdgeInsets.all(0),
                  keyboardType: TextInputType.numberWithOptions(decimal: true), // 允许数字和小数点
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}')), // 只允许数字和最多两位小数
                  ],
                  onTextChanged: (value) {
                    controller.withdrawalAmount.value = value;
                  },
                ),
              ),

              Text(
                '全部提现',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // --- 微信、支付宝 ---
  Widget weChatOrAliPayWidget() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //上传收款码
          Container(
            width: double.infinity,
            padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 24),
            decoration: BoxDecoration(
              color: Color(0x33959595),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '上传收款码',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 12),
                Obx(() {
                  // 根据当前tab索引决定显示哪个图片
                  String? imagePath;
                  if (controller.tabController.index == 1) {
                    // 微信 tab
                    imagePath = controller.weChatImage.value;
                  } else if (controller.tabController.index == 2) {
                    // 支付宝 tab
                    imagePath = controller.aliPayImage.value;
                  }

                  return GestureDetector(
                    onTap: () =>
                        controller.selectImage(controller.tabController.index),
                    child: Container(
                      width: 105,
                      height: 105,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: imagePath != null
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(10),
                              child: Image.file(
                                File(imagePath),
                                width: 105,
                                height: 105,
                                fit: BoxFit.cover,
                              ),
                            )
                          : Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                   'assets/images/ic_upload_image.png',
                                  width: 39,
                                  height: 39,
                                ),
                                SizedBox(height: 12),
                                Text(
                                  '上传图片',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 12,
                                    fontWeight: FontWeight.w400,
                                  ),
                                ),
                              ],
                            ),
                    ),
                  );
                }),
              ],
            ),
          ),
          SizedBox(height: 10),
          //提现金额
          withdrawalAmount(),
          SizedBox(height: 6),

          getBottomWidget(),
        ],
      ),
    );
  }

  // --- USDT ---
  Widget usdtWidget() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //上传收款码
          Container(
            width: double.infinity,
            padding: EdgeInsets.only(left: 10, right: 10, top: 16, bottom: 16),
            decoration: BoxDecoration(
              color: Color(0x33959595),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Row(
              children: [
                Text(
                  '请选择主网络',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Expanded(child: Text(
                  'TRC20',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Color(0xFFFF383C),
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                )),
              ],
            ),
          ),
          SizedBox(height: 10),

          //钱包地址
          Container(
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Color(0x33959595),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '请填写钱包地址',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 25),
                Row(
                  children: [
                    Expanded(
                      child: NoneStyleInputField(
                        hintText: '请输入钱包地址',
                        contentPadding: EdgeInsets.all(0),
                        onTextChanged: (value) {
                          controller.walletAddress.value = value;
                        },
                      ),
                    ),
                    Text(
                      '全部提现',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          SizedBox(height: 6),
          getBottomWidget(),
        ],
      ),
    );
  }

  Widget getBottomWidget() { // 移除context参数
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '最低提现金额100元',
          style: TextStyle(
            color: Colors.white,
            fontSize: 13,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(height: 5),
        Obx(
          () => Text(
            controller.tipText.value,
            style: TextStyle(
              color: Colors.white60,
              fontSize: 13,
              fontWeight: FontWeight.w400,
              height: 2,
            ),
          ),
        ),
        SizedBox(height: 21),

        GradientButton(
          text: '确认提醒',
          margin: EdgeInsetsGeometry.all(0),
          onPressed: () {
            // 点击按钮时提交提现申请
            controller.submitWithdrawal(); // 移除context参数
          },
        ),
      ],
    );
  }
}

// --- SliverPersistentHeaderDelegate 用于固定 TabBar ---
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar _tabBar;

  _SliverAppBarDelegate(this._tabBar);

  @override
  double get minExtent => _tabBar.preferredSize.height;
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(color: const Color(0xFF0E0F26), child: _tabBar);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) => false;
}
